<%
    session.setAttribute("user_name", "robert");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Posting</title>
    <link rel="stylesheet" type="text/css" title="T1" href="stylesheet/progin.css" id="link_theme" />
	<link rel="stylesheet" type="text/css" title="T1" href="stylesheet/posting.css" />
		<meta name="description" content="RERGag, Make You Laughing" />
		<meta name="keywords" content="laugh" />
		<meta name="author" content="Robertus Theodore" />
		<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    </head>
    <body>
        <%-- <%@ include file="header.jsp" %> --%>

        <div class="main_container">
            <div id="preview"></div>

	<div align="left" style="width: 500px;" >

	<form id="posting_form" name="posting_form" method="post" action="PostingHandler.jsp" >
	<fieldset><legend>Posting Baru</legend>

	<label class="label_posting">Judul </label><input id="form_nama" class="input_posting" name="title" type="text"></input><br/>

	<label class="label_posting">Pilihan </label><input id="option_link" class="input_posting" type="radio" name="option" value="link" onclick="return link_enable()" />Link<br />
	<label class="label_posting"></label><input id="option_image" class="input_posting" type="radio" name="option" value="image"  onclick="return image_enable()"/>Image<br />
	<label class="label_posting"></label><input id="option_video" class="input_posting" type="radio" name="option" value="video" onclick="return video_enable()"/>Video<br />

	<label class="label_posting">Link</label><input class="input_posting" id="form_link" type="text" name="link_url" disabled ="disabled"  ></input><font id="linkValidator" class="validation"></font><br />
	<label class="label_posting">Deskripsi Link</label><textarea class="textarea_posting" id="form_link_description" name="link_description" rows="5" cols="25" disabled ="disabled"  ></textarea><br />

       
        <label class="label_posting">Video </label><input class="input_posting" id="form_video"  name="mov" type="text" disabled ="disabled"  /><br />

        <label class="label_posting">Tag </label><input class="input_posting" name="tag" type="text"/><br />
	<label class="label_posting">&nbsp;</label><input type="submit" class="input_posting" value="Posting"/>
        <input type="button" name="buttonPreview" class="input_posting" onclick="preview()" value="Preview"/>
        
        </form>
        
        <form id="posting_form_image" name="posting_form_image" method="post" action="posting.jsp" enctype="multipart/form-data">    
            <label class="label_posting">Image </label><input class="input_posting" name="gambar" type="file"  disabled ="disabled" /><br />
            <label class="label_posting" style="margin-bottom: 100px;">&nbsp;</label><input type="Submit" class="input_posting" onclick="return formImageProcess()" value="Upload Image"/>
        </form>
        </fieldset>
       
        <%@ page language="java" import="java.sql.*" %>
        <%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
        <%@ page import="java.util.List"%>  
        <%@ page import="java.util.Iterator"%>  
        <%@ page import="org.apache.commons.fileupload.*"%>  
        <%@ page import="org.apache.commons.fileupload.disk.*"%>  
        <%@ page import="org.apache.commons.fileupload.servlet.*"%> 

        <%
            String driver = "org.gjt.mm.mysql.Driver";
            Class.forName(driver).newInstance();

            Connection con=null;
            ResultSet rst=null;
            Statement stmt=null;

            try{
                    String url="jdbc:mysql://localhost:3306/progin_171_13509008?user=root";
                    con=DriverManager.getConnection(url);
                    stmt=con.createStatement();
            }
            catch(Exception e){
                    System.out.println(e.getMessage());
            }
           
            // get next id_content for image naming
            int curIDContent =0 ;
            rst=stmt.executeQuery("SELECT MAX(id_content) as id FROM content");
            while (rst.next()){
                curIDContent = Integer.parseInt(rst.getString("id"));
            }
            curIDContent++;
        %>
       
        <%!	  
	//Uploading File -- method to return file extension  
	String getFileExt(String xPath){  
  
            //Find extension  

            int dotindex = 0;	//extension character position  
            dotindex = xPath.lastIndexOf('.');  

            if (dotindex == -1){	// no extension	  
                return "";  
            }  

            int slashindex = 0;	//seperator character position  
            slashindex = Math.max(xPath.lastIndexOf('/'),xPath.lastIndexOf('\\'));  

            if (slashindex == -1){	// no seperator characters in string  
                return xPath.substring(dotindex);  
            }  

            if (dotindex < slashindex){	//check last "." character is not before last seperator  
                return "";  
            }  
            return xPath.substring(dotindex);  
	}
        %>

        <%  // Form Processing
            //to get the content type information from JSP Request Header
            String contentTypeFile = request.getContentType();
            // Check that we have a file upload request
                    if((contentTypeFile!= null) && (contentTypeFile.indexOf("multipart/form-data") >= 0)){
                        boolean isMultipart = FileUpload.isMultipartContent(request);  
                        //out.println("isMultipart="+isMultipart+"<br>");  

                        //Create variables for path, filename and extension  
                        //String newFilePath = application.getRealPath("/") + "images";  
                        //String newFilePath = "images/posting";  
                        String newFilePath = "C:/Users/Robert/Documents/NetBeansProjects/reryes/web/images/posting";
                        String pathToDatabase = "images/posting";
                        String newFileName =Integer.toString(curIDContent);     // file named with id content
                        String FileExt = "";  

                        // Create a factory for disk-based file items  
                        FileItemFactory factory = new DiskFileItemFactory();  

                        // Create a new file upload handler  
                        ServletFileUpload upload = new ServletFileUpload(factory);  

                        // Parse the request  
                        List /* FileItem */ items = upload.parseRequest(request);  

                        // Process the uploaded items  
                        Iterator iter = items.iterator();  
                        //Form fields   
                        while (iter.hasNext()) {
                            FileItem item = (FileItem) iter.next();  
                            /* item already exist in directory
                            if (item.isFormField()) {  
                                String name = item.getFieldName();  
                                String value = item.getString();  
                                if (name.equals("newFileName")) {  
                                        newFileName = value;  
                                }  
                                out.println("Form Field Name= " + name + "<br>");  
                                out.println("Form Field Value= " + value + "<br><br>");  
                            } 
                            */  
                             
                            String fieldName = item.getFieldName();  
                            String fileName = item.getName();  
                            FileExt = getFileExt(fileName);  
                            String contentType = item.getContentType(); 
                            // check file extension 
                            if (!contentType.equals("image/jpeg")){
                                out.println("Ekstensi File bukan Bertipe .jpeg");
                                //response.sendRedirect("testUpload.jsp");
                            }
                            
                            // extension valid
                            else {
                                boolean isInMemory = item.isInMemory();  
                                long sizeInBytes = item.getSize();  
                                //out.println("fieldName= " + fieldName + "<br>");  
                                //out.println("fileName= " + fileName + "<br>");  
                                //out.println("FileExt= " + FileExt + "<br>");  
                                //out.println("contentType= " + contentType + "<br>");  
                                //out.println("isInMemory= " + isInMemory + "<br>");  
                                //out.println("sizeInBytes= " + sizeInBytes + "<br>");
                                //out.println("path  = "+ newFilePath + "<br>");
                                if (fileName.equals("") || sizeInBytes==0){  
                                        out.println("Not a valid file.<br>No upload attempted.<br><br>");  
                                } else {  
                                    File uploadedFile = new File(newFilePath+"/", newFileName+FileExt);  
                                    try{  
                                            item.write(uploadedFile);  
                                            out.println( newFilePath +"\\"+newFileName+FileExt+ "\"");
                                            out.println(fileName+" was successfully uploaded as "+ newFileName+FileExt +".<br><br>");  
                                            out.println("<input type=\"button\" name=\"path\" value=\""+ newFilePath +"/"+newFileName+FileExt+"\"></input>");
                                            String pathFile = pathToDatabase+"/"+newFileName+FileExt;
                                            session.setAttribute("path", pathFile);
                                    }  
                                    catch (java.lang.Exception e) {  
                                            out.println("Errors prevented the file upload.<br>"+fileName+ " was not uploaded.<br><br>");  
                                    }  
                                }  
                            } 
                        }
                    }
    %>
        <div id ="message">
        
        </div>
	</div>
        <script type="text/javascript" src="script/posting.js"></script>
        <script type="text/javascript" src="script/progin.js"></script>
        
        </div>
    </body>
</html>
